package com.sanpu.kxe.business.trade.presenter;

import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;

import com.sanpu.kxe.business.trade.bean.BillTypeOutput;
import com.sanpu.kxe.business.trade.bean.TransactionOutput;
import com.sanpu.kxe.business.trade.contract.TransactionContract;
import com.sanpu.kxe.business.trade.model.TradeModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.jump.eventbus.FilterEvent;
import com.sanpu.kxe.utils.ToastUtil;
import com.sanpu.kxe.utils.VerifyUtil;

import java.math.BigDecimal;
import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：账单
 * Created by 薛勇军 on 2018/8/27.
 */

public class TransactionPresenter implements TransactionContract.Presenter {

    private TransactionContract.View mView;

    private CompositeSubscription mSubscription;

    private String beforeEdit;
    //是否重置了EditText的内容
    private boolean resetText = false;

    public TransactionPresenter(TransactionContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void getBillList(final int nowPage, FilterEvent mFilterEvent) {
        Subscription subscription = TradeModel.getInstance().getBillList(nowPage, mFilterEvent)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<TransactionOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showErrorText(e);
                        mView.showLoadMore(CommonConfig.LOADMOREFAIL);
                    }

                    @Override
                    public void onNext(List<TransactionOutput> transactionOutputs) {
                        if (transactionOutputs != null) {
                            mView.showTransactionListView(transactionOutputs, nowPage == 0);
                            if (transactionOutputs.size() < CommonConfig.PAGENUMER) {
                                mView.showLoadMore(CommonConfig.LOADMOREEND);
                            } else {
                                mView.showLoadMore(CommonConfig.LOADMORECOMPLETE);
                            }
                        } else {
                            mView.showLoadMore(CommonConfig.LOADMOREEND);
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void getBillType() {
        mView.showLoadingDialog(false);
        Subscription subscription = TradeModel.getInstance().getBillType()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<BillTypeOutput>>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(List<BillTypeOutput> billTypeOutputs) {
                        mView.showBillTypeView(billTypeOutputs);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public TextWatcher getTextWatcher(final EditText editText) {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (!resetText) {
                    Selection.getSelectionEnd(s);
                    beforeEdit = s.toString();
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    resetText = true;
                    CharSequence input = s.subSequence(start, start + count);
                    if (TextUtils.isEmpty(beforeEdit)) {
                        //初始为空不让输小数点
                        if (TextUtils.equals(".", input)) {
                            resetText(editText, "0.");
                        }
                    }
                    if (TextUtils.equals("0", beforeEdit)) {
                        //初始为0不让输数字
                        if (!TextUtils.isEmpty(input) &&
                                VerifyUtil.isNumeric(input.toString())) {
                            resetText(editText, input.toString());
                        }
                    }
                    String text = s.toString();
                    if (text.contains(".")) {
                        //初始包含小数点，小数点后限两位数字
                        String decimals = text.substring(text.lastIndexOf(".") + 1, text.length());
                        if (decimals.length() > 2) {
                            resetText(editText, beforeEdit);
                        }
                    }
                    resetText = false;
                } else {
                    resetText = false;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    if (!TextUtils.isEmpty(s.toString())) {
                        BigDecimal values = new BigDecimal(s.toString());
                        if (values.compareTo(new BigDecimal(1000000)) == 1) {
                            ToastUtil.showTextViewPrompt("最多可输入1000000");
                            resetText(editText, "1000000");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

    /**
     * 还原输入框内容
     */
    private void resetText(EditText input, String reset) {
        if (reset == null) reset = "";
        input.setText(reset);
        CharSequence text = input.getText();
        if (text != null) {
            Spannable spanText = (Spannable) text;
            Selection.setSelection(spanText, text.length());
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}